package com.example.musicapp.storage.dao.impl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.musicapp.storage.dao.HistorySearchDao;
import com.example.musicapp.storage.db.MyDatabaseHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tangan
 * @since 8
 */
public class HistoryDaoImpl implements HistorySearchDao {

    /**
     * 单例的这个历史记录dao
     */
    private static HistorySearchDao sHistoryDao = null;
    /**
     * 数据库帮助类
     */
    private MyDatabaseHelper mMyDatabaseHelper;

    /**
     * 把数据帮助类的东东传进来
     *
     * @param context 上下文
     */
    private HistoryDaoImpl(Context context) {
        mMyDatabaseHelper = MyDatabaseHelper.getInstance(context);
    }


    private SQLiteDatabase db;

    /**
     * 双重锁判定单例
     *
     * @param context 上下文
     * @return 返回单例对象
     */
    public static HistorySearchDao getInstance(Context context) {
        if (sHistoryDao == null) {
            synchronized (HistoryDaoImpl.class) {
                if (sHistoryDao == null) {
                    sHistoryDao = new HistoryDaoImpl(context);
                }
            }
        }
        return sHistoryDao;
    }


    @Override
    public List<String> findAllRecord() {
        db = mMyDatabaseHelper.getReadableDatabase();
        List<String> historyRecords = new ArrayList<>();
        Cursor cursor = db.query(MyDatabaseHelper.TABLE.HISTORY_NOTE, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            String record = cursor.getString(cursor.getColumnIndex("record"));

            historyRecords.add(record);
        }
        cursor.close();
        return historyRecords;
    }

    @Override
    public void deleteAllRecord() {
        db = mMyDatabaseHelper.getWritableDatabase();
        db.delete(MyDatabaseHelper.TABLE.HISTORY_NOTE,null,null);
    }

    @Override
    public void insertRecord(String string) {
        db = mMyDatabaseHelper.getWritableDatabase();
        try {
            ContentValues contentValues = new ContentValues();
            contentValues.put("record",string);
            db.insert(MyDatabaseHelper.TABLE.HISTORY_NOTE, null,contentValues);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean findOneRecord(String string) {
        db = mMyDatabaseHelper.getReadableDatabase();

        Cursor cursor = db.query(MyDatabaseHelper.TABLE.HISTORY_NOTE, null," record = ?" , new String[]{string}, null, null, null);
        return cursor.moveToNext();
    }

    @Override
    public int deleteOneRecord(String string) {
        db = mMyDatabaseHelper.getWritableDatabase();

        return db.delete(MyDatabaseHelper.TABLE.HISTORY_NOTE,"record =?", new String[]{string});
    }

}
